package com.sk.sourcecircle.activity.mine.act;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.dyhdyh.widget.loading.dialog.LoadingDialog;
import com.sk.sourcecircle.R;
import com.sk.sourcecircle.base.BaseActivity;
import com.sk.sourcecircle.callback.HandleDataCallBack;
import com.sk.sourcecircle.entity.BussinessInfo;
import com.sk.sourcecircle.utils.AppApi;
import com.sk.sourcecircle.utils.MyUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jzvd.JZVideoPlayer;
import cn.jzvd.JZVideoPlayerStandard;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

/**
 * Created by sk on 2017/11/23.
 */
@RuntimePermissions
public class MyBusinessActivity extends BaseActivity implements HandleDataCallBack {
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.call)
    LinearLayout call;
    @BindView(R.id.tv_xuqiu)
    EditText tvXuqiu;
    @BindView(R.id.ed_name)
    EditText edName;
    @BindView(R.id.ed_phone)
    EditText edPhone;
    @BindView(R.id.ed_qq)
    EditText edQq;
    @BindView(R.id.ed_wx)
    EditText edWx;
    @BindView(R.id.apply)
    TextView apply;
    @BindView(R.id.tv_describe1)
    TextView tvDescribe1;
    @BindView(R.id.tv_describe2)
    TextView tvDescribe2;
    @BindView(R.id.image)
    ImageView image;
    @BindView(R.id.videoplayer)
    JZVideoPlayerStandard videoplayer;
    private String phone;
    private LoadingDialog loadingDialog;


    @Override
    protected int getContentView() {
        return R.layout.activity_business;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        loadingDialog = MyUtils.getLoadingDialog(mContext, false);
        loadingDialog.show();
        AppApi.getBussiness(this, 0, this);
    }

    @Override
    public void onBackPressed() {
        if (JZVideoPlayer.backPress()) {
            return;
        }
        super.onBackPressed();
    }
    @Override
    protected void onPause() {
        super.onPause();
        JZVideoPlayer.releaseAllVideos();
    }

    @OnClick({R.id.back, R.id.call, R.id.apply})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.call:
                MyBusinessActivityPermissionsDispatcher.startCallWithPermissionCheck(this);
                break;
            case R.id.apply:
                List<EditText> editTexts = new ArrayList<>();
                edName.setTag("请输入您的姓名!");
                edPhone.setTag("请输入您的电话号码!");
                tvXuqiu.setTag("请输入您的需求!");
                editTexts.add(edName);
                editTexts.add(edPhone);
                editTexts.add(tvXuqiu);
                if (MyUtils.isFormat(mRootView, editTexts)) {
                    loadingDialog.show();
                    AppApi.addBussiness(edName.getText().toString(), tvXuqiu.getText().toString(), edPhone.getText().toString(), edWx.getText().toString(), edQq.getText().toString()
                            , MyBusinessActivity.this, 1, MyBusinessActivity.this);
                }
                break;
        }
    }

    @Override
    public void handlerSuccessData(String result, int tag) {
        loadingDialog.cancelDialog();
        switch (tag) {
            case 0:
                BussinessInfo bussinessInfo = JSON.parseObject(result, BussinessInfo.class);
                tvDescribe1.setText(bussinessInfo.getData().getCooperation_describe());
                tvDescribe2.setText(bussinessInfo.getData().getCooperation_describe2());
                Glide.with(mContext).load(bussinessInfo.getData().getJieshao_pic()).into(image);
                phone = bussinessInfo.getData().getManager();
                videoplayer.setUp(bussinessInfo.getData().getJieshao_av(), JZVideoPlayerStandard.SCREEN_WINDOW_NORMAL);
                videoplayer.thumbImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                Glide.with(mContext).load(bussinessInfo.getData().getAv_pic()).into(videoplayer.thumbImageView);

                break;
            case 1:
                Toast.makeText(mContext, "信息提交成功,请等待客服人员与您联系！", Toast.LENGTH_SHORT).show();
                finish();
                break;
        }

    }

    @Override
    public void handlerFailData(String failString, int tag) {
        loadingDialog.cancelDialog();
    }

    @Override
    public void handleErrorData(String error, int tag) {
        loadingDialog.cancelDialog();
    }


    @NeedsPermission({Manifest.permission.CALL_PHONE})
    void startCall() {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }


    // 向用户说明为什么需要这些权限（可选）
    @NeedsPermission({Manifest.permission.CALL_PHONE})
    void showRationaleForPhone(final PermissionRequest request) {
        new AlertDialog.Builder(mContext)
                .setMessage("源圈需要使用您的电话！")
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .show();
    }

    // 用户拒绝授权回调（可选）
    @NeedsPermission({Manifest.permission.CALL_PHONE})
    void showDeniedForPhone() {
        Toast.makeText(mContext, "拒绝", Toast.LENGTH_SHORT).show();
    }


    // 用户勾选了“不再提醒”时调用（可选）
    @NeedsPermission({Manifest.permission.CALL_PHONE})
    void showNeverAskForPhone() {
        new AlertDialog.Builder(mContext)
                .setMessage("您已禁止电话权限,请到设置中开启。")
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BASE) {
                            // 进入设置系统应用权限界面
                            Intent intent = new Intent(Settings.ACTION_SETTINGS);
                            startActivity(intent);
                            return;
                        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {// 运行系统在5.x环境使用
                            // 进入设置系统应用权限界面
                            Intent intent = new Intent(Settings.ACTION_SETTINGS);
                            startActivity(intent);
                            return;
                        }
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                })
                .show();
    }

    @SuppressLint("NeedOnRequestPermissionsResult")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        MyBusinessActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

}
